package com.kcwl.idea.plugins.docconverter;

import cn.hutool.core.collection.CollUtil;
import com.kcwl.idea.plugins.base.utils.StrUtil;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.javadoc.PsiDocComment;

import java.util.ArrayList;
import java.util.List;

public class DocUtil {
    /**
     * 判断是否导入了指定的包
     *
     * @param psiFile
     * @param pkg
     * @return
     */
    public static boolean hasImportPkg(PsiJavaFile psiFile, String pkg) {
        List<String> importStatements = getAllImportStatements(psiFile);
        if (CollUtil.isEmpty(importStatements)) {
            return false;
        }
        for (String importStatement : importStatements) {
            importStatement = StrUtil.removeAny(importStatement, "import", ";").trim();
            if (importStatement.equals(pkg)) {
                return true;
            }
        }
        return false;
    }

    public static PsiElement getPsiElementAtCaret(Editor editor, Project project) {
        // 获取光标位置
        int offset = editor.getCaretModel().getOffset();

        // 获取PsiFile对象
        PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
        if (psiFile != null) {
            // 根据光标位置获取PsiElement
            return psiFile.findElementAt(offset);
        }

        return null;
    }

    public static String getDescriptionText(PsiDocComment docComment) {
        if (docComment == null) {
            return null;
        }
        return StrUtil.removeCommentSymbols(docComment.getText());
    }

    /**
     * 获取已导入的依赖列表
     * @param psiFile
     * @return
     */
    public static List<String> getAllImportStatements(PsiJavaFile psiFile) {
        List<String> importPkgList = new ArrayList<>();
        PsiImportList importList = psiFile.getImportList();
        if (importList == null) {
            return new ArrayList<>(0);
        }
        PsiImportStatementBase[] importStatements = importList.getAllImportStatements();
        for (PsiImportStatementBase importStatement : importStatements) {
            String text = importStatement.getText();
            importPkgList.add(text);
        }
        return importPkgList;
    }
}
